var {
  addEvent,
} = require('../../utils/api');

import env from '../../utils/config';
import Base64 from '../../utils/base64';
import Crypto from '../../utils/crypto';
import methods from '../../utils/methods';
require('../../utils/hmac');
require('../../utils/sha1');

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    eventlevelValue: 0,
    eventLevel:'',
    eventTypeValue:0,
    eventType: '', //事件类别
    areaValue:'',
    uname:'',
    eventTitle: '', //事件标题
    eventDesc: '', //事件描述
    eventResult:'',//调解结果描述
    eventUserName: '', //当事人
    eventTel: '', //当事人预留联系方式
    tempFilePaths: [],
    tempFileUrl: [],
    areas:[],
    types:[],
    levels:[],
    areaSel:'',
    areaType:'',
    eventArea:'',//所属村居
  },

  onLoad: function (options) {
    let _this = this;
    _this.setData({
          areas: app.globalData.areaArray,
          types:app.globalData.typeArray,
          levels:app.globalData.levelArray,
          uname:app.globalData.userInfo.name
    })
  },

  //事件标题
  titleInput(e) {
    this.setData({
      eventTitle: e.detail.value
    })
  },
  bindPickerChangelevel: function (e) {
    console.log('e.detail.value=', e.detail.value)
    this.setData({
      eventLevel: this.data.levels[e.detail.value].label,
      eventlevelValue: this.data.levels[e.detail.value].value
    })
  },
  bindPickerChangeType: function (e) {
    console.log('e.detail.value=', e.detail.value)
    this.setData({
      eventType: this.data.types[e.detail.value].label,
      eventTypeValue: this.data.types[e.detail.value].value
    })
  },
  bindAreaPickerChange: function (e) {
    console.log('e.detail.value=', e.detail.value)
    this.setData({
      areaSel: this.data.areas[e.detail.value].label,
      areaValue: this.data.areas[e.detail.value].value
    })
  },

  nameInput(e) {
    console.log('e.detail.value==',e.detail.value)
    this.setData({
      eventUserName: e.detail.value
    })
  },
  telInput(e) {
    this.setData({
      eventTel: e.detail.value
    })
  },
  descInput(e) {
    this.setData({
      eventDesc: e.detail.value
    })
  },
  resultInput(e){
    console.log('---',this.data.eventResult)
    this.setData({
      eventResult: e.detail.value
    })
  },
  //点击确定按钮---掉接口录入数据
  enterIn() {
    if(!this.data.eventLevel || !this.data.eventType || !this.data.eventUserName || !this.data.areaValue || !this.data.eventTel || !this.data.eventDesc ){
        methods.showToast('请完善上报信息!')
        return;
      }
    let obj = {
      userId: app.globalData.id,
      eventTitle: this.data.eventTitle,
      eventLevel: this.data.eventlevelValue,
      eventType: this.data.eventTypeValue,
      eventUserName: this.data.eventUserName,
      eventTel: this.data.eventTel,
      eventDesc: this.data.eventDesc,
      eventResult:this.data.eventResult,
      eventStatus: 1, //新增为待分配
      eventClient: 'wechat',
      eventArea:this.data.areaValue,//村居
      fileUrl: this.data.tempFileUrl.join(','),
    }

    console.log(obj);

    addEvent(obj).then((res) => {
      console.log(res);
      if (res[0] == 200) { //插入成功
        wx.redirectTo({
          url: '../personalproblemok/index'
        })
      }
    })
  },
  //把已经解决的问题也需要上传做一个简要的登记
  enterout(){
    if(!this.data.eventUserName || !this.data.areaValue || !this.data.eventTel || !this.data.eventDesc ){
      methods.showToast('请完善上报信息!')
      return;
    }
    let obj = {
      userId: app.globalData.id,
      eventTitle: this.data.eventTitle,
      eventLevel: this.data.eventlevelValue,
      eventType: this.data.eventTypeValue,
      eventUserName: this.data.eventUserName,
      eventTel: this.data.eventTel,
      eventDesc: this.data.eventDesc,
      eventResult:this.data.eventResult,
      eventStatus: 3, //新增为待分配
      eventClient: 'wechat',
      eventArea:this.data.areaValue,//村居
      fileUrl: this.data.tempFileUrl.join(','),
    }

    console.log(obj);

    // if(!this.data.eventUserName || !this.data.eventTel || !this.data.eventDesc ||!this.data.areaValue){
    //     methods.showToast('缺少必选项')
    //     return;
    //   }

    // if(!this.data.eventResult){
    //   methods.showToast('请说明初步调解情况')
    //   return;
    // }
    

    addEvent(obj).then((res) => {
      console.log(res);
      if (res[0] == 200) { //插入成功
        wx.navigateBack({
          delta: 1,
        })
      }
    })

  },
  listimgclear: function (e) {
    let that = this;
    console.log("e", e.currentTarget.dataset.index);
    let o = e.currentTarget.dataset.index;
    let newArr = that.data.tempFilePaths;
    let urlArr = that.data.tempFileUrl;
    newArr.splice(o, 1);
    urlArr.splice(o, 1);
    that.setData({
      tempFilePaths: newArr,
      tempFileUrl: urlArr
    }, () => {
      // console.log('删除后的=1=',that.data.tempFilePaths);
      // console.log('删除后的=2=',that.data.tempFileUrl);
    });
  },
  //点击上传图片
  addimg: function () {
    let that = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: '',
      success: function (res) {
        console.log('res', res)
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            //打开相册
            that.chooseWxImageShop('album')
          } else if (res.tapIndex == 1) {
            //手机拍照
            that.chooseWxImageShop('camera')
          }
        }
      },
    })


  },
  chooseWxImageShop: function (type) {
    let that = this;
    wx.chooseMedia({
      count: 4,
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: (res) => {
        console.log('params', res)
        const params = res.tempFiles[0].tempFilePath
        if (!params) {
          methods.showToast("文件错误,请重试")
          return false
        }
        //获取年月日
        const date = new Date()
        const year = date.getFullYear()
        const month =
          date.getMonth() + 1 < 10 ?
          '0' + (date.getMonth() + 1) :
          date.getMonth() + 1
        const day =
          date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
        const hour = date.getHours()
        const minute = date.getMinutes()
        const second = date.getSeconds()
        const hm = date.getMilliseconds()
        const time = year +''+ month + ''+day + ''+hour + ''+minute + ''+second + ''+hm
        //获取文件后缀名
        const fileExt = params.substring(params.lastIndexOf('.') + 1)

        const aliyunFileKey = time + '.' + fileExt //拼接文件名
        const aliyunServerURL = env.uploadImageUrl
        const accessid = env.OSSAccessKeyId
        const policyBase64 = this.getPolicyBase64()
        const signature = this.getSignature(policyBase64)
        wx.uploadFile({
          url: aliyunServerURL,
          filePath: params,
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data",
          },
          method: 'POST',
          formData: {
            key: aliyunFileKey,
            policy: policyBase64,
            OSSAccessKeyId: accessid,
            signature: signature,
            success_action_status: '200',
          },
          success: function (res) {
            console.log('res-->', res)
            
            //页面显示的图片path
            let tempFilePaths1 = that.data.tempFilePaths;
            tempFilePaths1.push(params);
            that.setData({
              tempFilePaths: tempFilePaths1
            });

            wx.showToast({
              title: '添加图片成功',
            })

            //上传后台的图片名字
            let tempFileUrlArray = that.data.tempFileUrl;
            tempFileUrlArray.push(aliyunFileKey);
            that.setData({
              tempFileUrl: tempFileUrlArray //这个tempFilePaths就是最终要上传的图片
            }, () => {
              console.log(that.data.tempFileUrl);
            });

          },
          fail: function (err) {
            console.log('err-->', err)
            wx.showToast({
              title: '添加图片失败',
            })
          },
        })
      },
    })

  },
  //上传到阿里云
  getPolicyBase64: function () {
    let date = new Date()
    date.setHours(date.getHours() + env.timeout)
    let srcT = date.toISOString()
    const policyText = {
      expiration: srcT, //设置该Policy的失效时间
      conditions: [
        ['content-length-range', 0, 30 * 1024 * 1024], // 设置上传文件的大小限制,30mb
      ],
    }
    const policyBase64 = Base64.encode(JSON.stringify(policyText))
    return policyBase64
  },

  getSignature: function (policyBase64) {
    const accesskey = env.AccessKeySecret
    const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
      asBytes: true,
    })
    const signature = Crypto.util.bytesToBase64(bytes)
    return signature
  },
})